/*
 * Copyright 2011-2012 Redia A/S
 * 
 * This file is part of Redias Library App for Android.
 *
 *  Redia Library App for Android is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redia Library App for Android is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redia Library App for Android.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.libraryapp;

import java.io.ByteArrayOutputStream;
import java.net.URL;

import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import dk.redia.lib.log.Log;
import android.text.Html;
import android.text.SpannableString;
import android.text.util.Linkify;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ProgressBar;
import dk.redia.lib.model.AbsoluteId;
import dk.redia.lib.model.InfoGalleriModel;
import dk.redia.lib.model.InfoObject;
import dk.redia.lib.model.Media;
import dk.redia.lib.net.ImageCache;
import dk.redia.lib.net.ImageCacheListener;
import dk.redia.lib.utils.AppConfiguration;
import dk.redia.lib.utils.Base64;
import dk.redia.lib.utils.DateUtils;
import dk.redia.lib.utils.StringUtils;
import dk.redia.libraryapp.activityutils.LibraryAppActivity;
import dk.redia.libraryapp.utils.ResourceUtils;

public class NewsItemDetailsActivity extends LibraryAppActivity {

	protected static final String logTag = "NewsItemDetailsActivity";
	private InfoObject io;
	private int backgroundColor;

	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.newsitemdetails);
	    
	    backgroundColor  = getResources().getColor(R.color.customerPrimaryColor);
	    WebView wv = (WebView)findViewById(R.id.newsItemDetailsWebView);
	    wv.setBackgroundColor(backgroundColor);
	    
	    String infoObjectId = getIntent().getExtras().getString("infoObjectId");
	    if (infoObjectId == null) {
	    	// This should never happen, but just in case
	    	finish();
	    	return;
	    }
	    AbsoluteId absId = new AbsoluteId(infoObjectId);
	    io = InfoGalleriModel.getInstance().getInfoObject(absId);
	    if (io==null) {
	    	// This should never happen, but just in case
	    	finish();
	    	return;
	    }
	    String tmpHeadline = io.getHeadline(AppConfiguration.getInstance().getContentLanguage());;
    	if (tmpHeadline == null) tmpHeadline = "";
	    final String headline = tmpHeadline;

	    String tmpBody = io.getBody(AppConfiguration.getInstance().getContentLanguage());
	    if (tmpBody==null) {
	    	tmpBody = "";
	    }
	    
	    final String body = StringUtils.linkify(tmpBody);
	    String tmpSubHeadline = io.getSubHeadline(AppConfiguration.getInstance().getContentLanguage());
	    if (tmpSubHeadline==null) {
	    	tmpSubHeadline = "";
	    }
	    final String subHeadline = tmpSubHeadline;
	    Media m = io.getFirstImageMedia();
	    URL mediaUrl = null;
	    Drawable d = getResources().getDrawable(R.drawable.news_item_details_reserve_button_up);
	    Bitmap b = ((BitmapDrawable)d).getBitmap();
	    ByteArrayOutputStream stream = new ByteArrayOutputStream();
	    b.compress(CompressFormat.JPEG, 100, stream);
	    final byte[] buttonImageData = stream.toByteArray();
	    if (m!=null) {
	    	mediaUrl = m.getUrl();
	    }
	    final boolean showArrangementStart = io.getType()==InfoObject.TYPE_ARRANGEMENT;
	    final String arrangementStartHtml;
	    if (showArrangementStart) {
	    	arrangementStartHtml = "<div class=\"startTime\">" + DateUtils.formatTime(io.getArrangementStartTime()) + "</div>";
	    } else {
	    	arrangementStartHtml = "";
	    }
	    final boolean showReserveButton = io.hasMetaDataKey("reserver");
	    final String reserveButtonHtml;
	    if (showReserveButton) {
	    	reserveButtonHtml = "<img class=\"button_image\" src=\"data:image/jpeg;base64," + Base64.encodeToString(buttonImageData, Base64.DEFAULT) + "\" onclick=\"reserve();\">";
	    } else {
	    	reserveButtonHtml = "";
	    }
/*	    try {
	    	mediaUrl = new URL(ImageUrlUtils.getResizedImageUrl(mediaUrl.toExternalForm(), 200, 400, ImageUrlUtils.RESIZE_MODE_CROP_EDGES));
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }*/
	    if (m==null) {
	    	BitmapDrawable bd = (BitmapDrawable)getResources().getDrawable(ResourceUtils.getNoImageResourceId());
	    	setHtml(bd.getBitmap(), showArrangementStart, arrangementStartHtml, headline, subHeadline, showReserveButton, reserveButtonHtml, body);	    	
	    } else {
		    Log.d(NewsItemDetailsActivity.logTag, "Loading news item image from " + mediaUrl.toExternalForm());
		    ImageCache.getInstance().loadImage(mediaUrl, new ImageCacheListener() {
				public void imageLoaded(Bitmap img) {
					setHtml(img, showArrangementStart, arrangementStartHtml, headline, subHeadline, showReserveButton, reserveButtonHtml, body);
				}
			}, null, 103, 103);
	    }
	}
	
	public void setHtml(Bitmap img, 
			boolean showArrangementStart, 
			String arrangementStartHtml,
			String headline,
			String subHeadline, 
			boolean showReserveButton,
			String reserveButtonHtml,
			String body) {
		
	    View v = findViewById(R.id.newsItemDetailsWebView);
	    final WebView wv = (WebView)v;
		
		Log.d(NewsItemDetailsActivity.logTag, "Loaded news image through cache. Setting webview content");

		byte[] b = null;
		
		if (img!=null) {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			img.compress(CompressFormat.JPEG, 100, baos);
			b = baos.toByteArray();
		}
		wv.setWebChromeClient(new NewsItemDetailsWebChromeClient());
		wv.getSettings().setJavaScriptEnabled(true);
		wv.addJavascriptInterface(new JavascriptHostObject(), "hostObject");
		wv.loadDataWithBaseURL("", "<html>" + 
    			"<head>" + 
    			"		    			" + 
    			"<meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8" +
    			"\" >" + 
    			"		    			" + 
    			"<style type=\"text/css\">" + 
    			"body { color:#ffffff; font-family:helvetica neue,arial,sans-serif;font-size:12px }" + 
    			"a:link {color:#dddddd;}" + 
    			"a:visited {color:#dddddd;}" + 
    			"a:hover {color:#888888;}" + 
    			"a:active {color:#666666;}" + 
    			"" + 
    			".headline {" + 
    			"    font-family:helvetica neue,arial,sans-serif;" + 
    			"    font-size:24px;" + 
    			"    font-weight:bold;" + 
    			"    margin-bottom:12px;" + 
    			"}" +
    			".startTime {" +
    			"    font-family:helvetica neue,arial,sans-serif;" +
    			"    font-size:8px;" +
    			"    padding-bottom:10px;" +
    			"}" + 
    			"" + 
    			".subheadline {" + 
    			"    font-weight:bold;" + 
    			"    font-size:16px;" + 
    			"}" + 
    			"" + 
    			".frontpage_image {" + 
    			"    width:103px;" +
    			//"    min-height:103px;" + 
    			"    float:right;" + 
    			"    clear:right;" + 
    			"    padding:3px;" + 
    			"}" + 
    			"" + 
    			".button_image {" + 
    			"    width:103px;" + 
    			"    height:27px;" + 
    			"    float:right;" + 
    			"    padding:3px;" + 
    			"}" + 
    			"" + 
    			".body {" + 
    			"    font-size:14px;" + 
    			"}" + 
    			".main {" + 
    			"    width:280px;" + 
    			"}" + 
    			"" + 
    			"</style>" +
    			"<script type=\"text/javascript\">" +
    			"    var reserve = function() {" + 
    			"        hostObject.reserve();" +
    			"    };" +
    			"</script>" +
    			"</head>" + 
    			"<body>" + 
    			"<div class=\"main\">" + 
    			"    <div class=\"headline\">" + headline + "</div>" + 
    			(showArrangementStart ? arrangementStartHtml : "") +
    			"    <hr>" + 
    			"    <div class=\"subheadline\">" + subHeadline + "</div>" + 
    			"    <div class=\"body\">" +
    			(showReserveButton ? reserveButtonHtml : "") +  // Only show reserve button if meta data contained information
    			// Only show an image if we have one
    			(b==null ? "" : "        <img class=\"frontpage_image\" src=\"data:image/jpeg;base64," + Base64.encodeToString(b, Base64.DEFAULT) + "\">") + 
    			         body + 
    			"    </div>" + 
    			"</div>" + 
    			"</body>" + 
    			"</html>", "text/html", "UTF-8", null);
    	// Transparent background to make the layout color show through
    	//wv.setBackgroundColor(0x00000000);
    	wv.setBackgroundColor(backgroundColor);
    	AlphaAnimation aa = new AlphaAnimation(1, 0);
    	final ProgressBar pb = (ProgressBar)findViewById(R.id.newsItemDetailsProgressBar);
    	aa.setDuration(1000);
    	aa.setAnimationListener(new Animation.AnimationListener() {
			
			public void onAnimationStart(Animation animation) {}
			
			public void onAnimationRepeat(Animation animation) {}
			
			public void onAnimationEnd(Animation animation) {
				pb.setVisibility(View.INVISIBLE);
			}
		});
    	pb.startAnimation(aa);
	}
	
	public void reserve() {
		Log.d(NewsItemDetailsActivity.logTag, "Request for reserve for info object " + io.getAbsoluteId());
		if (io!=null) {
		}
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
		return true;
	}

	private final class NewsItemDetailsWebChromeClient extends WebChromeClient {
	    @Override
	    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
	        Log.d(NewsItemDetailsActivity.logTag, message);
	        new AlertDialog.Builder(view.getContext()).setMessage(message).setCancelable(true).show();
	        result.confirm();
	        return true;
	    }
	}
	
	private final class JavascriptHostObject {
		@SuppressWarnings("unused")
		/**
		 * This get's called by javascript inside the webview on another thread,
		 * so all interaction with stuff needs to be posted to the UI thread or done
		 * asynchronously
		 */
		public void reserve() {
			Log.d(NewsItemDetailsActivity.logTag, "reserve()");
			runOnUiThread(new Runnable() {
				public void run() {
					// TODO Auto-generated method stub
					// FIXME Launch a reserve activity, on the correct thread
				}
			});
		}
	}
}
